package com.groupbuying.currency.consumer.mq;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.groupbuying.currency.consumer.service.OperCurrencyService;
import com.groupbuying.currency.consumer.utils.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * class_name: CurrencyMsgListener package: com.groupbuying.currency.consumer.mq description:
 * 积分中心MQ消息监听器 creat_user: Ywxd creat_date: 2019/5/20 creat_time: 15:26
 **/
@Component
public class CurrencyMsgListener implements MessageListener {

    public static final Logger LOGGER = LoggerFactory.getLogger(CurrencyMsgListener.class);


    @Autowired
    private CurrencyPayResult currencyAddResult;
    @Autowired
    private OperCurrencyService operCurrencyService;
    @Autowired
    private CurrencyPayNotify currencyPayNotify;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        if (!message.getTopic().equals(CurrencyMQConfig.TOPIC) || StringUtils.isEmpty(message.getTag())) {
            LOGGER.error("Topic不符合订阅要求，Topic：" + message.getTopic() + "或者Tag为空，Tag：" + message.getTag());
            return Action.CommitMessage;
        }
        /* 获取消息重试次数 */
        int reconsume = message.getReconsumeTimes();
        if (reconsume >= 3) {
            /* 消息已经重试了超过或等于3次，告诉服务器稍后再尝试消费 */
            return Action.ReconsumeLater;
        }
        //解析消息体
        Map<String, Object> result = JSONUtils.jsonToMap(new String(message.getBody()));
        /**
         * 通过TAG来判断处理方式
         *
         */
        LOGGER.info("获取消息：{}" ,result.toString());
        boolean handleResult = false;
        //微信支付回执处理
        if (message.getTag().equals(CurrencyMQConfig.CURRENCY_ADD)) {

            handleResult = currencyAddResult.currencyAddResult(result);
            //积分支付回执处理
        }else if (CurrencyMQConfig.TAG_PAY_TO_FINANCIAL.equals(message.getTag())){
            handleResult = operCurrencyService.sendMqForSubOrderCurrency(result);
        }else if(message.getTag().equals(CurrencyMQConfig.TAG_PAY_FOR_SENDMESSAGE)){
            //小程序消息通知处理
            handleResult = currencyPayNotify.CurrencyNotify(result);
        } else if(message.getTag().equals(CurrencyMQConfig.TAG_REBACK_CURRENCY)){
            //线上支付退款，积分回填
            handleResult = currencyAddResult.onlinePayRebackCurrency(result);
        }
        if (!handleResult) {
            LOGGER.error("处理失败；Tag：{}" ,message.getTag());
        }
        return  Action.CommitMessage;
}
}


